package redis

import (
	"errors"
	"fmt"
	"gitee.com/xuxinzhi2206/corehub/nacos"
	"gitee.com/xuxinzhi2206/corehub/types"
	"github.com/go-redis/redis"
	"gopkg.in/yaml.v2"
)

func RedisClient(hand func(rdb *redis.Client) error) error {
	initNacos, err := nacos.GetConfig()
	config := types.Configs
	err = yaml.Unmarshal([]byte(initNacos), &config)
	if err != nil {
		return err
	}
	addr := fmt.Sprintf("%s:%d", config.Redis.Host, config.Redis.Port)
	rdb := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: config.Redis.Password, // no password set
		DB:       0,                     // use default DB
	})

	defer rdb.Close()

	_, err = rdb.Ping().Result()
	if err != nil {
		return errors.New("redis is not client error: " + err.Error())
	}
	fmt.Println("redis connection successful")

	return hand(rdb)
}
